package com.shengqin.controller.exam;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shengqin.annotations.OperaLog;
import com.shengqin.common.pojo.CommonPage;
import com.shengqin.common.pojo.CommonResult;
import com.shengqin.config.CommonException;
import com.shengqin.controller.api.dto.TestResultUploadParam;
import com.shengqin.controller.api.dto.UploadScoreItem;
import com.shengqin.entity.Arbitrate;
import com.shengqin.entity.Plan;
import com.shengqin.entity.PlanApplyProject;
import com.shengqin.entity.TestResult;
import com.shengqin.enums.BusinessType;
import com.shengqin.pojo.exam.ArbitrateQueryParam;
import com.shengqin.pojo.plan.result.ImportTestResultParam;
import com.shengqin.pojo.plan.result.ScoreResult;
import com.shengqin.service.IArbitrateService;
import com.shengqin.service.IPlanApplyProjectService;
import com.shengqin.service.IPlanService;
import com.shengqin.service.ITestResultService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@RestController
@RequestMapping("admin/v1/arbitrate")
@Slf4j
public class ArbitrateController {

    @Resource
    private IArbitrateService arbitrateService;
    @Resource
    private IPlanApplyProjectService applyProjectService;
    @Resource
    private IPlanService planService;
    @Resource
    private ITestResultService testResultService;

    @PostMapping("queryPage")
    public CommonResult<Page<Arbitrate>> queryPage(@RequestBody CommonPage<ArbitrateQueryParam> queryPageParam){
        return CommonResult.data(arbitrateService.queryPage(queryPageParam));
    }

    @OperaLog(title = "仲裁申请", businessType = BusinessType.INSERT)
    @PostMapping("save")
    public CommonResult<Boolean> onSave(@RequestBody Arbitrate arbitrate){
        log.info("仲裁提交入参 {}", JSON.toJSONString(arbitrate));
        PlanApplyProject planApplyProject = applyProjectService.getById(arbitrate.getApplyId());
        if(arbitrate.getId() == null){
            arbitrate.setCreateTime(LocalDateTime.now());
            arbitrate.setCreateUserId(Integer.valueOf(StpUtil.getLoginId().toString()));
            if(planApplyProject != null){
                arbitrate.setStudyCode(planApplyProject.getStudyCode());
                arbitrate.setName(planApplyProject.getName());
                arbitrate.setSchoolId(planApplyProject.getSchoolId());
            }
        }
        return CommonResult.data(arbitrateService.saveOrUpdate(arbitrate));
    }

    @OperaLog(title = "仲裁审核", businessType = BusinessType.UPDATE)
    @PostMapping("review")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Boolean> review(@RequestBody Arbitrate arbitrate){
        log.info("仲裁审核入参 {}", JSON.toJSONString(arbitrate));
        if(arbitrate.getState().equalsIgnoreCase("审核通过")){
            Arbitrate oldArbitrate = arbitrateService.getById(arbitrate.getId());
            Plan plan = planService.getById(oldArbitrate.getPlanId());

            List<String> studyCodes = new ArrayList<>();
            studyCodes.add(oldArbitrate.getStudyCode());
            List<TestResult> testResults = testResultService.listByPlanIdAndStudyCodes(plan.getId(),studyCodes);

            List<TestResult> prjTestResults = testResults.stream().filter(item -> item.getPrjName().equalsIgnoreCase(arbitrate.getProjectName())).collect(Collectors.toList());

            if(CollectionUtils.isEmpty(prjTestResults)){
                throw new CommonException("未查询到原成绩，请再次确认！");
            }

            TestResult testResult = prjTestResults.get(0);

            TestResultUploadParam testResultUploadParam = new TestResultUploadParam();
            testResultUploadParam.setPlanId(plan.getCode());

            List<UploadScoreItem> scoreResults = new ArrayList<>();
            UploadScoreItem scoreItem = new UploadScoreItem();
            scoreItem.setResult(arbitrate.getNewResult());
            scoreItem.setPrjName(oldArbitrate.getProjectName());
            scoreItem.setStudyCode(oldArbitrate.getStudyCode());
            scoreItem.setDeviceNo(testResult.getDeviceNo());
            scoreItem.setTestEndTime(testResult.getTestEndTime());
            scoreItem.setTestStartTime(testResult.getTestStartTime());
            scoreItem.setCameraId(testResult.getCameraId());
            scoreResults.add(scoreItem);
            testResultUploadParam.setScoreList(scoreResults);

            List<ImportTestResultParam> cachedDataList = new ArrayList<>();
            if(!CollectionUtils.isEmpty(testResultUploadParam.getScoreList())){
                testResultUploadParam.getScoreList().forEach(uploadScoreItem -> {
                    ImportTestResultParam importTestResultParam = new ImportTestResultParam();
                    BeanUtils.copyProperties(uploadScoreItem,importTestResultParam);
                    cachedDataList.add(importTestResultParam);
                });
                testResultService.importBatch(cachedDataList,plan.getId(),"arbitrate");
            }
        }

        return CommonResult.data(arbitrateService.updateById(arbitrate));
    }

    @OperaLog(title = "删除仲裁记录", businessType = BusinessType.DELETE)
    @PostMapping("delete")
    public CommonResult<Boolean> delete(@RequestBody Arbitrate arbitrate){
        log.info("仲裁删除入参 {}", JSON.toJSONString(arbitrate));
        return CommonResult.data(arbitrateService.removeById(arbitrate.getId()));
    }

}
